<template>
  <div class="main-div">
    <Row>
      <Col span="24" />

      <Card>
        <p slot="title">业务实体</p>

        <Form ref="formInline" :model="formInline" :label-width="80" inline :rules="ruleValidate">
          <FormItem prop="groupName" label="分类">
            <treeselect
              v-model="formInline.groupName"
              :normalizer="normalizer"
              :multiple="false"
              placeholder="请选择"
              :options="categoryData"

              @select="selectTree"
              @input="clearOnSelect"
            />

          </FormItem>

          <FormItem prop="tableName" label="表名">
            <Input v-model="formInline.tableName" type="text" :disabled="edit" clearable />
          </FormItem>

          <FormItem prop="modelName" label="实体名称">
            <Input v-model="formInline.modelName" type="text" :disabled="edit" clearable />
          </FormItem>
          <FormItem v-if="this.formInline.type == 'external'" prop="modelName" label="数据库表">
            <treeselect
              v-model="formInline.tableName"
              :normalizer="existTableNormalizer"
              :multiple="false"
              :disabled="edit"

              placeholder="请选择"
              :options="existTableData"
              @select="selectExistTableTree"
              @input="clearExistTableOnSelect"
            />
          </FormItem>
          <Form-item v-if=" formInline.type=='inner'" prop="dsName" label="是否生成物理表" :label-width="120">
            <el-tag
              v-if="(formInline.createdTable===false ||formInline.createdTable==='false') && formInline.type=='inner'"
              type="success"
            >
              否

            </el-tag>
            <el-tag
              v-else-if="(formInline.createdTable===true ||formInline.createdTable==='true') && formInline.type=='inner'"
              type="success"
            >
              是

            </el-tag>
            <FormItem>

              <Button
                v-if="(formInline.createdTable===false ||formInline.createdTable==='false' ) && formInline.id && formInline.type=='inner'"
                type="primary"
                style="margin-bottom: 2px;margin-right: 15px;"
                @click="createTable"
              >生成表
                <el-tooltip class="item" effect="dark" placement="top-start">
                  <div slot="content">生成表之前，请确保已经保存了字段信息。<br>字段信息一旦生成，不允许进行删除操作
                  </div>

                </el-tooltip>
              </Button>
              <Button
                v-else-if="(formInline.createdTable===true ||formInline.createdTable==='true')&& formInline.type=='inner'"
                type="primary"
                @click="createTable"
              >更新表
              </Button>

            </FormItem>

          </Form-item>
          <FormItem prop="description" label="描述">
            <Input v-model="formInline.description" type="text" clearable />
          </FormItem>
        </Form>

        <el-button v-if="formInline.type=='inner'" type="primary" @click="add">添加字段</el-button>
        <el-button type="primary" :loading="loading" @click="save">保存</el-button>
      </Card>

      <Card style="margin-top: 5px">
        <p slot="title">字段</p>
        <el-form
          ref="ruleForm"
          :model="ruleForm"
          :rules="rules"

          style="margin-top: 10px"
        >
          <el-table
            :data="ruleForm.tableData"
            border
          >
            <el-table-column label="描述" fixed>

              <template slot-scope="scope">
                <el-form-item :prop="'tableData.' + scope.$index + '.description'">
                  <el-input v-model="scope.row.description" style="width:100%" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              label="数据库字段名"
              fixed
            >
              <template slot-scope="scope">

                <el-form-item :prop="'tableData.' + scope.$index + '.columnKey'" :rules="rules.columnKey">
                  <el-tooltip class="item" effect="dark" placement="top-start">
                    <div slot="content">请满足数据库列的相关命名格式.<br>不要使用数据库的关键词、Java和JS关键词
                      <br>
                      首位可以是字母以及下划线。首位之后可以是字母，数字以及下划线。下划线后不能接下划线
                    </div>

                    <el-input
                      v-model="scope.row.columnKey"
                      style="width:100%"
                      :disabled="operateDisabled(scope.row)"
                    />
                  </el-tooltip>

                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="必填">
              <template slot-scope="scope">
                <el-form-item :prop="'tableData.' + scope.$index + '.required'">
                  <el-checkbox v-model="scope.row.required" :disabled="operateDisabled(scope.row)" />
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column label="类型">
              <template slot-scope="scope">

                <el-form-item :prop="'tableData.' + scope.$index + '.dataType'">

                  <el-select
                    v-model="scope.row.dataType"
                    placeholder="请选择"
                    :disabled="operateDisabled(scope.row)"
                    @change="((val)=>{selectDataTypeChanged(val, scope.$index)})"
                  >
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>

                </el-form-item>

              </template>
            </el-table-column>
            <el-table-column label="格式">
              <template slot-scope="scope">
                <el-form-item :prop="'tableData.' + scope.$index + '.format'">
                  <el-select
                    v-if="scope.row.dataType=='date'"
                    v-model="scope.row.format"
                    :disabled="operateDisabled(scope.row)"
                  >
                    <el-option
                      v-for="item in formatOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>

                </el-form-item>

              </template>
            </el-table-column>
            <el-table-column label="整数长度">

              <template slot-scope="scope">
                <el-form-item :prop="'tableData.' + scope.$index + '.attrLength'" :rules="rules.attrLength">
                  <el-input
                    v-if="scope.row.dataType=='varchar'|| scope.row.dataType=='number'"
                    v-model.number="scope.row.attrLength"
                    :disabled="operateDisabled(scope.row)"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="小数长度">

              <template slot-scope="scope">
                <el-form-item :prop="'tableData.' + scope.$index + '.decimalLength'" :rules="rules.decimalLength">
                  <el-input
                    v-if="scope.row.dataType=='number'"
                    v-model="scope.row.decimalLength"
                    :disabled="operateDisabled(scope.row)"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="默认值">
              <template slot-scope="scope">
                <el-form-item :prop="'tableData.' + scope.$index + '.defaultValue'">
                  <el-input v-model="scope.row.defaultValue" :disabled="operateDisabled(scope.row)" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-form-item>
                  <el-button v-if="operateDisabledDelBtn(scope.row)" type="danger" plain @click="delField(scope.$index)">
                    删除
                  </el-button>

                </el-form-item>

              </template>
            </el-table-column>

          </el-table>

        </el-form>

      </Card>

      <!--        <Table border  ref="currentRowTable" height="450"-->
      <!--               :columns="tableColumns" :data="tableData" style="padding-left: 10px;padding-top: 10px">-->
      <!--        </Table>-->
      </Col>

    </Row>
  </div>

</template>

<script>
import { getTaskData } from '@/api/analy'
// import the component
import Treeselect from '@riophae/vue-treeselect'
// import the styles
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import {
  getTypesByKey,
  getBusinessTableListJson,
  businessTableSave,
  businessTableGet,
  businessTableCreate,
  businessTableColumnDelete,
  businessTableColumnMetadataInfo,
  businessTableColumnMetadataInfoByTableName
} from '@/api/form'
import { isColumnKey, attrLengthValidator } from '@/utils/validate'

export default {
  name: 'Task',
  components: { Treeselect },

  data() {
    return {
      loading: false,

      edit: false,
      ruleForm: {
        tableData: []
      },
      rules: {
        description: [{ required: true, message: '  ', trigger: 'blur' }],
        decimalLength: [{ required: true, message: '  ', trigger: 'blur' }],
        attrLength: [{
          validator: attrLengthValidator,
          trigger: 'blur'
        }],
        columnKey: [{ required: true, message: '  ', trigger: 'blur' }, { validator: isColumnKey, trigger: 'blur' }]
      },

      options: [{
        value: 'varchar',
        label: '字符串'
      }, {
        value: 'number',
        label: '数字型'
      }, {
        value: 'date',
        label: '日期型'
      }, {
        value: 'clob',
        label: '大文本'
      }],
      tableFormRules: {
        description: { type: 'string', required: true, message: '必填字段', trigger: 'change' }
      },
      ruleValidate: {
        groupName: [
          { required: true, message: '请选择分类', trigger: 'change' }
        ],
        tableName: [
          { required: true, message: '请输入表名', trigger: 'blur' }
        ],
        modelName: [
          { required: true, message: '请输入实体名称', trigger: 'blur' }
        ]
      },
      // define the default value
      value: null,
      value: '',
      formatOptions: [{
        value: 'yyyy-MM-dd HH:mm:ss',
        label: 'yyyy-MM-dd HH:mm:ss'
      }, {
        value: 'yyyy-MM-dd',
        label: 'yyyy-MM-dd'
      }, {
        value: 'HH:mm:ss',
        label: 'HH:mm:ss'
      }],
      formatValue: 'yyyy-MM-dd HH:mm:ss',
      formInline: {
        createdTable: 'false',
        dsKey: '',
        dsName: '',
        groupId: '',
        groupName: null,
        modelName: '',
        tableName: null,
        description: '',
        type: 'inner',
        id: ''
      },

      tableData: [],
      tableColumns: [

        {
          title: '注释',
          editable: true,
          key: 'description',
          rules: [{ required: true, message: '代理人必须填写', trigger: 'blur' }]

        },
        {
          title: '数据库字段名',
          key: 'columnKey',
          val: '',
          editable: true
        },
        {
          title: '必填',
          key: 'required',
          val: ''

        },
        {
          title: '类型',
          key: 'dataType',
          val: 'varchar'

        },
        {
          title: '格式',
          key: 'format',
          val: ''

        },
        {
          title: '整数长度',
          key: 'attrLength',
          val: ''

        },
        {
          title: '小数长度',
          key: 'decimalLength',
          val: ''

        },
        {
          title: '默认值',
          key: 'defaultValue',
          val: ''

        },
        {
          title: '操作',
          key: 'operate',
          val: ''

        }

      ],
      tableHeight: 450,
      queryDate: [],
      total: 0,
      chartVisible: false,
      chartData: {},
      sellerId: 0,
      shopName: [],
      queryForm: {
        groupId: '',
        page: 0,
        limit: 10
      },
      categoryData: [],
      existTableData: [],
      existData: []
    }
  },
  mount() {
    this.getData()
    this.tableHeight = window.innerHeight - this.$refs.table.$el.offsetTop
  },
  created() {
    var query = this.$route.query
    var operate = query.operate
    var edit = query.edit
    if (edit) {
      this.edit = JSON.parse(edit)
    } else {

    }

    if (query.id) {
      this.formInline.id = query.id
      this.initData()
    }
    if (operate) {
      this.formInline.type = operate
    }
    this.initExternal()
    this.getData()
  },

  methods: {
    initExternal: function() {
      if (this.formInline.type == 'external') {
        businessTableColumnMetadataInfo().then((response) => {
          if (response.code == 0) {
            this.existTableData = response.data
          }
        })
      }
    },
    operateDisabled: function(data) {
      if (this.formInline.type == 'inner' && (this.formInline.createdTable == 'false' || this.formInline.createdTable == false)) {
        return false
      } else if (this.formInline.type == 'inner' && (this.formInline.createdTable == 'true' || this.formInline.createdTable == true)) {
        if (data.id) {
          return true
        } else {
          return false
        }
      }
      return true
    },
    operateShowExistdData: function(data) {
      if (this.formInline.type == 'external') {
        return true
      } else {
        return false
      }
    },
    operateDisabledDelBtn: function(data) {
      if (this.formInline.type == 'inner' && (this.formInline.createdTable == 'false' || this.formInline.createdTable == false)) {
        return true
      } else if (this.formInline.type == 'inner' && (this.formInline.createdTable == 'true' || this.formInline.createdTable == true)) {
        if (data.id) {
          return false
        } else {
          return true
        }
      }
      return false
    },
    createTable: function() {
      this.save()
      businessTableCreate(this.formInline.id).then((response) => {
        if (response.code == 0) {
          this.$message({ 'duration': 800, message: '操作成功', type: 'warning', customClass: 'zZindex' })

          this.initData()
        } else {
          this.$message({ 'duration': 800, message: response.msg, type: 'warning', customClass: 'zZindex' })
        }
      })
    },
    initData: function() {
      if (this.formInline.id) {
        businessTableGet(this.formInline.id).then((response) => {
          if (response.code == 0) {
            var data = response.data
            var formBusinessEntity = data.formBusinessEntity
            var formBusinessModelColumnEntityList = data.formBusinessModelColumnEntityList
            if (formBusinessEntity) {
              this.formInline.groupId = formBusinessEntity.groupId
              this.formInline.groupName = formBusinessEntity.groupName
              this.formInline.modelName = formBusinessEntity.modelName
              this.formInline.tableName = formBusinessEntity.tableName
              this.formInline.description = formBusinessEntity.description
              this.formInline.type = formBusinessEntity.type
              this.formInline.createdTable = formBusinessEntity.createdTable
            }
            if (formBusinessModelColumnEntityList) {
              this.ruleForm.tableData = formBusinessModelColumnEntityList
              this.existData = formBusinessModelColumnEntityList
            }
          }
        })
      }
    },
    selectTree: function(node, instanceId) {
      this.formInline.groupId = node.id
      this.formInline.groupName = node.title
      this.validateFormInline()
    },

    clearOnSelect: function(node, instanceId) {
      if (!node) {
        this.formInline.groupId = ''
        this.formInline.groupName = null
        this.validateFormInline()
      }
    },
    clearExistTableOnSelect: function(node, instanceId) {
      if (!node) {
        this.formInline.tableName = null
        this.validateFormInline()
      }
    },
    selectExistTableTree: function(node, instanceId) {
      businessTableColumnMetadataInfoByTableName(node.tableName).then((response) => {
        if (response.code == 0) {
          var data = response.data
          this.ruleForm.tableData = data
        }
      })
    },
    validateRuleForm: function() {
      this.$nextTick(() => {
        this.$refs['ruleForm'].validate((valid) => {

        })
      })
    },
    validateFormInline: function() {
      this.$nextTick(() => {
        this.$refs['formInline'].validate((valid) => {

        })
      })
    },
    save: function() {
      this.$refs['formInline'].validate((valid) => {
        if (valid) {
          var data = {}
          var formData = this.formInline
          data['formBusinessEntity'] = formData

          this.$refs['ruleForm'].validate((valid2) => {
            if (valid2) {
              var tableData = this.ruleForm.tableData
              if (tableData.length == 0) {
                this.$message({ 'duration': 800, message: '请选择字段', type: 'warning', customClass: 'zZindex' })

                return
              }
              data['formBusinessModelColumnEntityList'] = tableData
              this.loading = true
              businessTableSave(data).then((response) => {
                if (response.code == 0) {
                  this.formInline.id = response.tableId
                  this.$message({ 'duration': 800, message: '保存成功', type: 'warning', customClass: 'zZindex' })

                  this.initData()
                } else {
                  this.$message({ 'duration': 800, message: response.msg, type: 'warning', customClass: 'zZindex' })
                }
                this.loading = false
              })
            }
          })
        } else {
        }
      })
    },
    selectDataTypeChanged: function(value, index) {
      if (value == 'number') {
        this.ruleForm.tableData[index].attrLength = '10'
        this.ruleForm.tableData[index].decimalLength = '0'
      } else if (value == 'varchar') {
        this.ruleForm.tableData[index].attrLength = '50'
      } else if (value == 'date') {
        this.ruleForm.tableData[index].format = this.formatValue
      }
    },

    delField: function(index) {
      // 如果存在id 调用接口删除数据库的
      if (this.ruleForm.tableData[index].id) {
        businessTableColumnDelete(this.ruleForm.tableData[index].id).then((response) => {
          if (response.code == 0) {
          }
        })
      }

      // businessTableColumnDelete

      this.ruleForm.tableData.splice(index, 1)
      this.$message({ 'duration': 800, message: '操作成功', type: 'warning', customClass: 'zZindex' })
    },
    disabledDelBtn: function(row) {
      for (var i = 0; i < this.existData.length; i++) {
        if (row === this.existData[i]) {
          return true
        }
      }
      return false
    },
    handleSubmit: function(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.$Message.success('Success!')
        } else {
          this.$Message.error('Fail!')
        }
      })
    },
    add: function() {
      this.ruleForm.tableData.push(
        {
          'description': '',
          'columnKey': '',
          'required': false,
          'dataType': 'varchar',
          'attrLength': '50',
          'decimalLength': '0',
          'defaultValue': '',
          'newColumn': true

        }
      )
      this.validateRuleForm()
    },
    queryFormCreateTime: function(e) {
      this.queryForm.createTime = e
    },
    refreshTask: function(data) {
      if (data[0].parentId == '-1') {
        this.queryForm.typeKey = ''
      } else {
        this.queryForm.typeKey = data[0].typeKey
      }
      this.queryForm.createTime = ''
      this.queryDate = []
      this.queryForm.whereSql = ''
      this.getData()
    },
    queryMethod: function() {
      var name = this.queryForm.name
      var whereSql = ''
      var createTime = this.queryForm.createTime
      if (createTime) {
        if (createTime[0]) {
          whereSql = "  CREATE_TIME_  between '" + createTime[0] + "' and " + "'" + createTime[1] + "'"
        }
      }
      this.queryForm.whereSql = whereSql
      getTaskData(this.queryForm).then((response) => {
        this.tableData = response.data
        if (response.count.length > 0) {
          this.total = parseInt(response.count)
        } else {
          this.total = 0
        }
      })
    },
    // 后台返回的数据如果和VueTreeselect要求的数据结构不同，需要进行转换
    normalizer(node) {
      // 去掉children=[]的children属性
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.title,
        label: node.title,
        children: node.children
      }
    },
    existTableNormalizer(node) {
      return {
        id: node.tableName,
        label: node.tableComment,
        children: node.children
      }
    },
    getData: function() {
      getTypesByKey().then((response) => {
        this.categoryData = response.data
      })
    },
    handleCurrentChange(val) {
      this.queryForm.page = val
      this.getData()
    },
    handleClick(data) {
      this.$router.push({ name: 'handleRunTask', query: { t: new Date().getTime(), 'taskId': data.id }})
    },
    search() {
      this.queryForm.page = 0
      this.queryMethod()
    },
    reset() {
      this.queryForm.name = ''
      this.queryForm.createTime = ''
      this.queryForm.whereSql = ''
      this.queryDate = []
      this.getData()
    }

  }

}

</script>
<style lang="scss" scoped>
  .main-div {
    background-color: #f3f3f3!important;
  }
  .task-card {
    margin-top: 10px;
  }

  .vue-treeselect {
    max-width: 180px;
  }

  .cell {
    max-height: 54px !important;
    overflow: auto !important;
  }

</style>
